package sunwin.yois.web.common.resolverArg;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

/**
 * Created by mt on 2015-9-6.
 */
public class ResolverUUIDArg  implements HandlerMethodArgumentResolver {
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterAnnotation(YoisUUIDParam.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String paraName = parameter.getParameterName();
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        String paraValue = request.getParameter(paraName);

        if (paraValue != null) {
            try {
                return UUID.fromString(paraValue);
            } catch (Exception ex) { }
        }
        return null;
    }
}
